package com.atXiao.gpt.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 */
public class ResBody extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public ResBody setData(Object data) {
        return put("data", data);
    }

    //手动进行自定义类型转换
    public <T> T getData(TypeReference<T> typeReference) {
        //默认为map类型
        Object data = get("data");
        String res = JSON.toJSONString(data);
        T t = JSON.parseObject(res, typeReference);
        return t;
    }


    public ResBody() {
        put("code", 000000);
        put("msg", "success");
    }

    public static ResBody error() {
        return error(500, "系统繁忙，请稍后再试");
    }

    public static ResBody error(String msg) {
        return error(500, msg);
    }

    public static ResBody error(int code, String msg) {
        ResBody resBody = new ResBody();
        resBody.put("code", code);
        resBody.put("msg", msg);
        return resBody;
    }

    public static ResBody ok(String msg) {
        ResBody resBody = new ResBody();
        resBody.put("msg", msg);
        return resBody;
    }

    public static ResBody ok(Map<String, Object> map) {
        ResBody resBody = new ResBody();
        resBody.putAll(map);
        return resBody;
    }

    public static ResBody ok() {
        return new ResBody();
    }

    public ResBody put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public int getCode() {
        return (int) this.get("code");
    }


}
